package com.tencent.wxcloudrun.service.impl;

import com.tencent.wxcloudrun.common.utils.Constant;
import com.tencent.wxcloudrun.vo.Catalog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.wxcloudrun.common.utils.PageUtils;
import com.tencent.wxcloudrun.common.utils.Query;

import com.tencent.wxcloudrun.dao.CategoryDao;
import com.tencent.wxcloudrun.model.CategoryEntity;
import com.tencent.wxcloudrun.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Cacheable(value = Constant.CACHE_NAME, key = "#root.method.name")
    public List<CategoryEntity> listWithTree() {
        //1. 查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2. 组装成父子的树形结构
        return entities.stream().filter(categoryEntity ->
                //找到所有的根目录, 递归查找其子菜单
                categoryEntity.getParentCid() == 0
        ).peek(categoryEntity ->
                categoryEntity.setChildren(getChildren(categoryEntity, entities))
        ).sorted((menu1, menu2) ->
                menu1.getSort() == null ? 0 : menu1.getSort() - (menu2.getSort() == null ? 0 : menu2.getSort())
        ).collect(Collectors.toList());
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {

    }


    //找到categoryId的完整路径
    @Override
    public Long[] findCatalogPath(Long categoryId) {
        //存储三级分类路径
        List<Long> path = new ArrayList<>();
        findParentPath(categoryId, path);

        return path.toArray(new Long[0]);
    }

    @Override
    public void updateCascade(CategoryEntity category) {

    }


    //查询所有一级分类
    @Override
    public List<CategoryEntity> findLevelOneCategory() {
        System.out.println("findLevelOneCategory()方法调用");
        return baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0)
        );
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        return selectList.stream().filter(item -> item.getParentCid().equals(parentCid))
                .collect(Collectors.toList());
    }


    //获取分类json数据
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //优化:先查出所有数据
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1.查出所有一级分类
        List<CategoryEntity> levelOneCategorys = getParentCid(selectList, 0L);

        //2.封装数据
        Map<String, List<Catalog2Vo>> map = levelOneCategorys.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            //3.查到所有二级分类
            List<CategoryEntity> levelTwoCategorys = getParentCid(selectList, v.getCatId());
            //4. 封装指定vo
            List<Catalog2Vo> catalog2Vos = null;
            if (levelTwoCategorys != null) {
                catalog2Vos = levelTwoCategorys.stream().map(l2 -> {
                    //5. 找当前二级分类的三级分类
                    List<CategoryEntity> levelThreeCategorys = getParentCid(selectList, l2.getCatId());

                    //将三级分类封装为vo
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if (levelThreeCategorys != null) {
                        catalog3Vos = levelThreeCategorys.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString()
                                    , l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }

                    //catalog2Vo
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString()
                            , catalog3Vos, l2.getCatId().toString(), l2.getName());

                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return map;
    }

    @Override
    public List<CategoryEntity> getLevel2Categories() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("cat_level", 2));
    }


    private void findParentPath(Long categoryId, List<Long> path) {
        CategoryEntity categoryEntity = this.getById(categoryId);
        if(categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), path);
        }
        path.add(categoryEntity.getCatId());
    }


    //在总数组all中找到菜单root的所有子菜单, 递归查找
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all){
        return all.stream().filter(categoryEntity ->
                //在总数组中过滤出父菜单id等于root菜单id的值, 即root的子菜单
                categoryEntity.getParentCid().equals(root.getCatId())
        ).peek(categoryEntity ->
                //对于root的子菜单, 递归查找其子子菜单
                categoryEntity.setChildren(getChildren(categoryEntity, all))
        ).sorted((menu1, menu2) ->
                //排序
                menu1.getSort() == null ? 0 : menu1.getSort() - (menu2.getSort() == null ? 0 : menu2.getSort())
        ).collect(Collectors.toList());
    }

}